package com.loveyukari.dao.impl;

import com.loveyukari.dao.AddressDao;
import com.loveyukari.model.Address;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class JdbcAddressDao extends BaseDao implements AddressDao{

    private RowMapper<Address> addressRowMapper = new RowMapper<Address>() {
        @Override
        public Address mapRow(ResultSet resultSet, int i) throws SQLException {
            Address address = new Address();
            address.setId(resultSet.getInt("id"));
            address.setAddress(resultSet.getString("address"));
            address.setName(resultSet.getString("name"));
            address.setPhone(resultSet.getString("phone"));
            address.setAuthId(resultSet.getInt("auth_id"));
            return address;
        }
    };


    @Override
    public List<Address> selectByAuth(int authId) {
        String sql = "select * from auth_address where auth_id = ? and status = 0";
        List<Address> list = this.getJdbcTemplate().query(sql, addressRowMapper, authId);
        return list;
    }

    @Override
    public void insert(Address address) {
        String sql = "insert into auth_address (address,name,phone,auth_id) values(?,?,?,?)";
        this.getJdbcTemplate().update(sql,address.getAddress(),address.getName(),address.getPhone(),address.getAuthId());
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        String sql = "update auth_address set status = ? where id = ?";
        this.getJdbcTemplate().update(sql,status,id);
    }

    @Override
    public Address select(Integer id) {
        String sql = "select * from auth_address where id = ?";
        List<Address> list = this.getJdbcTemplate().query(sql, addressRowMapper, id);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }
}
